<template>
  <div class="orders-page">
    <h2>我的订单</h2>
    
    <!-- 订单状态筛选 -->
    <div class="filter-bar">
      <el-radio-group v-model="statusFilter" @change="handleFilterChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="unpaid">待付款</el-radio-button>
        <el-radio-button label="paid">已付款</el-radio-button>
        <el-radio-button label="shipped">已发货</el-radio-button>
        <el-radio-button label="completed">已完成</el-radio-button>
        <el-radio-button label="cancelled">已取消</el-radio-button>
        <el-radio-button label="refunded">已退款</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 订单列表 -->
    <div v-loading="loading" class="orders-list">
      <el-empty v-if="!loading && orders.length === 0" description="暂无订单" />
      
      <div v-for="order in orders" :key="order.id" class="order-card">
        <div class="order-header">
          <span class="order-no">订单号：{{ order.orderNo }}</span>
          <span class="order-time">{{ formatDate(order.createTime) }}</span>
          <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
        </div>
        
        <div class="order-items">
          <div v-for="item in order.items" :key="item.id" class="order-item">
            <el-image :src="getImageUrl(item.productImage)" class="item-image" fit="cover" />
            <div class="item-info">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-price">¥{{ item.price }} × {{ item.quantity }}</div>
            </div>
            <div class="item-subtotal">¥{{ item.subtotal }}</div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-total">
            <span>订单总额：</span>
            <span class="amount">¥{{ order.totalAmount }}</span>
          </div>
          <div class="order-actions">
            <el-button v-if="order.status === 'unpaid'" type="danger" size="small" @click="handleCancelOrder(order)">
              取消订单
            </el-button>
            <el-button v-if="order.status === 'shipped'" type="success" size="small" @click="handleReceiveOrder(order)">
              确认收货
            </el-button>
            <el-button 
              v-if="['paid', 'shipped', 'completed'].includes(order.status)" 
              type="warning" 
              size="small" 
              @click="handleApplyRefund(order)">
              申请退货
            </el-button>
            <el-button type="primary" size="small" plain @click="viewOrderDetail(order)">
              查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 退货申请对话框 -->
    <el-dialog v-model="refundDialogVisible" title="申请退货" width="500px">
      <el-form :model="refundForm" :rules="refundRules" ref="refundFormRef" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="currentOrder.orderNo" disabled />
        </el-form-item>
        <el-form-item label="退款金额">
          <el-input v-model="currentOrder.totalAmount" disabled>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="退货原因" prop="refundReason">
          <el-input
            v-model="refundForm.refundReason"
            type="textarea"
            :rows="4"
            placeholder="请输入退货原因（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitRefund">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderList, cancelOrder, receiveOrder } from '@/api/order'
import { applyRefund } from '@/api/refund'
import { useRouter } from 'vue-router'

const router = useRouter()

const loading = ref(false)
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')

const refundDialogVisible = ref(false)
const currentOrder = ref({})
const refundForm = ref({
  orderId: null,
  refundReason: ''
})
const refundFormRef = ref(null)
const submitting = ref(false)

const refundRules = {
  // 退款原因改为非必填
  refundReason: []
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const res = await getOrderList({
      page: currentPage.value,
      pageSize: pageSize.value,
      status: statusFilter.value
    })
    if (res.code === 200) {
      orders.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '加载订单列表失败')
    }
  } catch (error) {
    console.error('加载订单列表失败', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 状态筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
  loadOrders()
}

// 分页变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadOrders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadOrders()
}

// 取消订单
const handleCancelOrder = (order) => {
  ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await cancelOrder(order.id)
      if (res.code === 200) {
        ElMessage.success('订单已取消')
        loadOrders()
      } else {
        ElMessage.error(res.message || '取消订单失败')
      }
    } catch (error) {
      console.error('取消订单失败', error)
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {})
}

// 确认收货
const handleReceiveOrder = (order) => {
  ElMessageBox.confirm('确认已收到商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const res = await receiveOrder(order.id)
      if (res.code === 200) {
        ElMessage.success('确认收货成功')
        loadOrders()
      } else {
        ElMessage.error(res.message || '确认收货失败')
      }
    } catch (error) {
      console.error('确认收货失败', error)
      ElMessage.error('确认收货失败')
    }
  }).catch(() => {})
}

// 申请退货
const handleApplyRefund = (order) => {
  currentOrder.value = order
  refundForm.value = {
    orderId: order.id,
    refundReason: ''
  }
  refundDialogVisible.value = true
}

// 提交退货申请
const submitRefund = async () => {
  submitting.value = true
  try {
    const res = await applyRefund(refundForm.value)
    if (res.code === 200) {
      ElMessage.success('退货申请已提交，请等待处理')
      refundDialogVisible.value = false
      loadOrders()
    } else {
      ElMessage.error(res.message || '提交退货申请失败')
    }
  } catch (error) {
    console.error('提交退货申请失败', error)
    ElMessage.error('提交退货申请失败')
  } finally {
    submitting.value = false
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push(`/customer/orders/${order.id}`)
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    unpaid: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    unpaid: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return textMap[status] || status
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取图片URL
const getImageUrl = (image) => {
  if (!image) return ''
  if (image.startsWith('http://') || image.startsWith('https://')) return image
  return `http://localhost:8080/${image.startsWith('/') ? image.slice(1) : image}`
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped lang="scss">
.orders-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .orders-list {
    .order-card {
      margin-bottom: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .order-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        background: #f7f8fa;
        border-bottom: 1px solid #ebeef5;

        .order-no {
          font-size: 14px;
          color: #606266;
        }

        .order-time {
          font-size: 14px;
          color: #909399;
        }
      }

      .order-items {
        padding: 20px;

        .order-item {
          display: flex;
          align-items: center;
          margin-bottom: 15px;

          &:last-child {
            margin-bottom: 0;
          }

          .item-image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            margin-right: 15px;
          }

          .item-info {
            flex: 1;

            .item-name {
              font-size: 16px;
              color: #303133;
              margin-bottom: 8px;
            }

            .item-price {
              font-size: 14px;
              color: #909399;
            }
          }

          .item-subtotal {
            font-size: 16px;
            color: #f56c6c;
            font-weight: bold;
          }
        }
      }

      .order-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        background: #f7f8fa;
        border-top: 1px solid #ebeef5;

        .order-total {
          font-size: 16px;
          color: #303133;

          .amount {
            color: #f56c6c;
            font-size: 20px;
            font-weight: bold;
            margin-left: 10px;
          }
        }

        .order-actions {
          display: flex;
          gap: 10px;
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
